<!DOCTYPE html>
<html>

<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>promise的介绍</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
    <script src='main.js'></script>
</head>

<body>

</body>
<script>
    //promise是异步编程的一种解决方案，用来优化回调地狱，比传统的解决方案--回调函数更为合理
    //案例 请求接口
    let api = new Promise((resolve, reject) => {
        setTimeout(() => {
            if (true) {//传递pending状态
                resolve('ok')//resolve表示成功的回调，传递fulfilled状态
            } else {
                reject('error')//reject表示失败的回调，传递rejected状态
            }
        }, 2000)
    })
    api.then((res) => {//fulfilled执行then函数
        console.log(res);
        console.log('promise请求成功');
    })
        .catch((err) => {//rejected执行catch函数
            console.log(err);
            console.log('promise请求失败');
        })
        //promise对象通过自身的状态，控制异步操作，promise有三种状态
        //异步操作未完成 --- pending 
        //异步操作成功 --- fulfilled
        //异步操作失败 --- rejected
</script>

</html>